package com.example.test

import android.annotation.SuppressLint
import android.app.Notification
import android.content.Context
import android.content.Intent
import android.os.Build
import io.flutter.plugin.common.EventChannel

@SuppressLint("OverrideAbstract")
class NotificationListener() : android.service.notification.NotificationListenerService() {
    companion object {
        var eventConsumer: EventChannel.EventSink? = null
    }
    fun setEventCallback(eventCallback: EventChannel.EventSink) {
        eventConsumer = eventCallback
    }
    fun startListening(appContext: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            appContext.startService(
                Intent(
                    appContext,
                    NotificationListener::class.java
                )
            )
        }
    }

    fun stopListening(appContext: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            appContext.stopService(
                Intent(
                    appContext,
                    NotificationListener::class.java
                )
            )
        }
    }

    override fun onNotificationPosted(sbn: android.service.notification.StatusBarNotification) {
        val packageName = sbn.packageName
        println("收到消息：${packageName}")
        if (packageName == "com.tencent.mm" || packageName == "com.tencent.mobileqq") {
            val notification = sbn.notification
            val title = notification.extras.getString(Notification.EXTRA_TITLE)
            val text = notification.extras.getString(Notification.EXTRA_TEXT)
            val message = "Package: $packageName, Title: $title, Text: $text"
            println("消息内容：${message}")
            eventConsumer?.success(message)
        }
    }
}
